package day_7_11;

import java.util.ArrayList;
import java.util.List;

public class Main2 {
    /**
     * 114. 二叉树展开为链表
     * https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/description/?envType=study-plan-v2&envId=top-100-liked
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    List<TreeNode> list = new ArrayList<>();

    public void flatten(TreeNode root) {
        // 使用先序遍历拿到每一个节点
        preorder(root);
        // 这时候 list 中就是按照先序遍历排序的每一个节点
        // 根据这个顺序在原树上进行修改
        int size = list.size();
        for(int i = 1;i < size;i++) {
            TreeNode prve = list.get(i - 1);
            TreeNode cur = list.get(i);
            prve.left = null;
            prve.right = cur;
        }
    }

    public void preorder(TreeNode root) {
        if(root == null) {
            return;
        }
        list.add(root);
        preorder(root.left);
        preorder(root.right);
    }
}
